<template>
  <div class="page-container">
    <div class="header">
      <h1>我的</h1>
      <div class="header-right">
        <div class="notification-icon-wrapper" @click="goToNotification">
          <el-icon :size="24" class="notification-icon">
            <Bell />
          </el-icon>
          <span v-if="hasUnread" class="notification-badge-dot"></span>
        </div>
      </div>
    </div>
    <div class="content">
      <el-card class="info-card">
        <div class="card-content">
          <div class="user-info" v-if="userInfo">
            <div class="avatar">
              <el-icon :size="40"><User /></el-icon>
            </div>
            <h3>{{ userInfo.username }}</h3>
            <p>欢迎使用健研社</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="menu-card">
        <div class="menu-item" @click="goToVerify">
          <span>实名认证</span>
          <el-icon><Right /></el-icon>
        </div>
        <el-divider style="margin: 0;" />
        <div class="menu-item" @click="goToCustomerService">
          <span>我的客服</span>
          <el-icon><Right /></el-icon>
        </div>
        <el-divider style="margin: 0;" />
        <div class="menu-item" @click="handleLogout">
          <span style="color: #f56c6c;">退出登录</span>
          <el-icon><Right /></el-icon>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { User, Right, Bell } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useNotificationStore } from '@/stores/notification'
import { checkIdcardAuth } from '@/api/verify'

const router = useRouter()
const userStore = useUserStore()
const notificationStore = useNotificationStore()

// 直接使用 store 中的 userInfo，保持状态一致
const userInfo = computed(() => userStore.userInfo)

// 是否有未读消息
const hasUnread = computed(() => notificationStore.hasUnread)

onMounted(() => {
  // 从 localStorage 获取用户信息并同步到 store
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userStore.setUserInfo(JSON.parse(storedUserInfo))
  }
})

// 身份证号加密处理：显示前6位和后4位，中间用*代替
const maskIdCard = (idcard) => {
  if (!idcard || idcard.length !== 18) {
    return idcard
  }
  return idcard.substring(0, 6) + '********' + idcard.substring(14)
}

const goToVerify = async () => {
  // 获取用户ID
  const storedUserInfo = localStorage.getItem('userInfo')
  if (!storedUserInfo) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  const userInfoData = JSON.parse(storedUserInfo)
  const userId = userInfoData.id
  
  if (!userId) {
    ElMessage.error('用户信息异常，请重新登录')
    return
  }
  
  const loading = ElLoading.service({
    lock: true,
    text: '查询认证状态...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    console.log('查询认证状态，user_id:', userId)
    const response = await checkIdcardAuth(userId)
    loading.close()
    
    console.log('认证状态查询结果:', response)
    
    if (response.code === 200) {
      const data = response.data
      
      // 根据 is_real 状态区分已认证和待审核
      if (data.is_real === 1) {
        // 已实名认证，展示信息
        const { name, idcard_number } = data
        const maskedIdCard = maskIdCard(idcard_number)
        
        // 使用 catch 捕获用户点击关闭按钮的情况
        await ElMessageBox.alert(
          `<div style="padding: 20px 0;">
            <p style="margin: 12px 0; font-size: 15px;">
              <span style="color: #909399; display: inline-block; width: 100px;">姓名：</span>
              <span style="font-weight: 600;">${name}</span>
            </p>
            <p style="margin: 12px 0; font-size: 15px;">
              <span style="color: #909399; display: inline-block; width: 100px;">身份证号：</span>
              <span style="font-weight: 600; letter-spacing: 1px;">${maskedIdCard}</span>
            </p>
          </div>`,
          '实名认证信息',
          {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true
          }
        ).catch(() => {
          // 用户点击关闭按钮或按 ESC 键，不做任何处理
        })
      } else if (data.is_real === 2) {
        // 待审核状态，显示提示信息
        const message = data.message || '您的实名认证正在审核中，请耐心等待1-3个工作日'
        await ElMessageBox.alert(
          `<div style="padding: 20px 0; text-align: center;">
            <p style="margin: 12px 0; font-size: 16px; color: #E6A23C;">
              ⏳ 审核中
            </p>
            <p style="margin: 12px 0; font-size: 14px; color: #606266;">
              ${message}
            </p>
          </div>`,
          '实名认证信息',
          {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true
          }
        ).catch(() => {})
      } else if (data.is_real === 0) {
        // 未实名认证，进入认证页面
        console.log('用户未认证')
        router.push('/verify')
      }
    } else if (response.code === 400) {
      // 未实名认证，进入认证页面
      console.log('用户未认证:', response.message)
      router.push('/verify')
    } else {
      ElMessage.warning(response.message || response.msg || '查询认证状态失败')
    }
  } catch (error) {
    loading.close()
    console.error('查询认证状态失败:', error)
    ElMessage.error('查询认证状态失败: ' + (error.message || '未知错误'))
  }
}

const goToNotification = () => {
  router.push('/notification')
}

const goToCustomerService = () => {
  router.push('/customer-service')
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch {
    // 用户取消操作
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100%;
  background-color: #f5f7fa;
}

.header {
  background: white;
  padding: 0 16px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
}

.notification-icon-wrapper {
  position: relative;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-icon {
  color: #606266;
  transition: color 0.3s;
}

.notification-icon-wrapper:hover .notification-icon {
  color: #409eff;
}

.notification-badge-dot {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 8px;
  height: 8px;
  background-color: #f56c6c;
  border-radius: 50%;
  border: 2px solid #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.1);
  }
}

.content {
  padding: 16px 16px 80px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 56px);
}

.info-card {
  width: 100%;
  margin-bottom: 16px;
}

.card-content {
  text-align: center;
  padding: 20px;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  color: #909399;
}

.user-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
}

.user-info p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.menu-card {
  width: 100%;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item:hover {
  opacity: 0.7;
}

.menu-item span {
  font-size: 15px;
  color: #f56c6c;
}
</style>

